package com.xxx.meter.base;

import android.app.AlertDialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseDialog extends AlertDialog {

    private Unbinder bind;
    private View view;
    private double widthRate = 1; //0.85是占据屏幕宽的比例
    private boolean isSquare = false; //是否是正方形

    protected BaseDialog(Context context) {
        super(context);
        initWindow();   //初始化参数
    }

    protected BaseDialog(Context context, double widthRate, boolean isSquare) {
        super(context);
        this.widthRate = widthRate;
        this.isSquare = isSquare;
        initWindow();   //初始化参数
    }

    private void initWindow() {
        setCancelable(true); // 是否可以按“返回键”消失
        setCanceledOnTouchOutside(false); // 点击框以外的区域

        //渲染布局
        view = LayoutInflater.from(getContext()).inflate(getLayoutId(), null);
        bind = ButterKnife.bind(this, view);
    }

    /**
     * 展示Dialog
     */
    @Override
    public void show() {
        super.show();
        if (view != null) {
            setContentView(view);
            //设置大小
            final Window window = getWindow();
            if (window != null) {
                final WindowManager.LayoutParams lp = window.getAttributes();
                window.setBackgroundDrawableResource(android.R.color.transparent);
                window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                window.getDecorView().post(new Runnable() {
                    @Override
                    public void run() {
                        lp.width = (int) (window.getDecorView().getWidth() * widthRate);
                        if (isSquare) {
                            lp.height = lp.width;
                        }
                        window.setGravity(Gravity.CLIP_HORIZONTAL);
                        window.setAttributes(lp);
                        initData();
                    }
                });
            }
        }
    }

    /**
     * 隐藏布局Dialog
     */
    @Override
    public void dismiss() {
        super.dismiss();
        if (bind != null) {
            bind.unbind();
            bind = null;
        }
        if (view != null) {
            view.clearAnimation();
            view.clearFocus();
            view = null;
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initData();

}
